package com.lmt.config.shiro;

import lombok.extern.log4j.Log4j2;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author MT-Lin
 */
@Log4j2
@Component
@SuppressWarnings("unchecked")
public class ShiroRedisSessionDao extends AbstractSessionDAO{

    /**
     * Session超时时间，单位为毫秒
     */
    private long expireTime = 120000;
    private static final String PREFIX_SHIRO_SESSION = "shiro-redis-session:";

    private RedisTemplate redisTemplate;

    @Autowired
    public ShiroRedisSessionDao(RedisTemplate redisTemplate) {
        super();
        this.redisTemplate = redisTemplate;
    }

    /**
     * 更新session
     */
    @Override
    public void update(Session session) throws UnknownSessionException {
        log.info("com.lmt.config.shiro.ShiroRedisSessionDao#update");
        if (session == null || session.getId() == null) {
            return;
        }
        session.setTimeout(expireTime);
        redisTemplate.opsForValue().set(getSessionKey(session), session, expireTime, TimeUnit.MILLISECONDS);
    }

    @Override // 删除session
    public void delete(Session session) {
        log.info("com.lmt.config.shiro.ShiroRedisSessionDao#delete");
        if (null == session) {
            return;
        }
        redisTemplate.opsForValue().getOperations().delete(getSessionKey(session));
    }

    // 获取活跃的session，可以用来统计在线人数，如果要实现这个功能，可以在将session加入redis时指定一个session前缀，统计的时候则使用keys("session-prefix*")的方式来模糊查找redis中所有的session集合
    @Override
    public Collection<Session> getActiveSessions() {
        log.info("com.lmt.config.shiro.ShiroRedisSessionDao#getActiveSessions");
        List<Session> objects = redisTemplate.opsForValue().multiGet(redisTemplate.keys(getSessionKey("*")));
        if (null == objects){
            return new ArrayList<>();
        }
        return objects;
    }

    @Override// 加入session
    protected Serializable doCreate(Session session) {
        log.info("com.lmt.config.shiro.ShiroRedisSessionDao#doCreate");
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);

        redisTemplate.opsForValue().set(getSessionKey(session), session, expireTime, TimeUnit.MILLISECONDS);
        return sessionId;
    }

    @Override // 读取session
    protected Session doReadSession(Serializable sessionId) {
        log.info("com.lmt.config.shiro.ShiroRedisSessionDao#doReadSession");
        if (sessionId == null) {
            return null;
        }
        return (Session) redisTemplate.opsForValue().get(getSessionKey(sessionId));
    }

    public long getExpireTime() {
        return expireTime;
    }

    public void setExpireTime(long expireTime) {
        this.expireTime = expireTime;
    }

    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private String getSessionKey(Session session) {
        return PREFIX_SHIRO_SESSION + session.getId().toString();
    }

    private String getSessionKey(Serializable sessionId) {
        return PREFIX_SHIRO_SESSION + sessionId.toString();
    }
}
